package com.yuexun.dhdoctor.module.Contract.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.adapter.ContractAdapter;
import com.yuexun.dhdoctor.module.Contract.adapter.DepartmentListAdapter;
import com.yuexun.dhdoctor.module.Contract.bean.GroupDataBean;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.Contract.bean.UsersBean;
import com.yuexun.dhdoctor.module.Contract.model.impl.DepartmentModel;
import com.yuexun.dhdoctor.module.Contract.presenter.impl.DepartmentPresenter;
import com.yuexun.dhdoctor.module.Contract.ui.Act_PeopleDetail;
import com.yuexun.dhdoctor.module.Contract.ui.view.IDepartmentView;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;

import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/7/17.
 */
public class Frag_Department extends Fragment implements IDepartmentView {

    @Bind(R.id.dept_back)
    ImageView deptBack;
    @Bind(R.id.dept_title_tv)
    TextView deptTitleTv;
    @Bind(R.id.dept_list)
    FixedSwipeListView deptList;
    @Bind(R.id.people_list)
    FixedSwipeListView peopleList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.back_view)
    RelativeLayout backView;

    private DepartmentPresenter presenter;

    private BaseAdapter adapter_dept;
    private ContractAdapter adapter_people;
    List<GroupDataBean> datas;
    GroupDataBean groupDataBean;
    int parentDepartmentId;
    int hospitalId;
    int oldHospitalId;

    public void setHospitalId(int hospitalId) {
        this.hospitalId = hospitalId;
        refrshView();
    }

    private void refrshView() {
        if (hospitalId != oldHospitalId) {
            backView.setVisibility(View.GONE);
            initPresent();
            oldHospitalId = hospitalId;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_department, null);
        ButterKnife.bind(this, view);
        initView(view);
        initData();
        return view;
    }

    void initData() {
        parentDepartmentId = 0;
        hospitalId = PreferenceHelper.readInt(getActivity(), AppConfig.USER_INFO, AppConfig.HOSPITALID);
        oldHospitalId = hospitalId;
        initPresent();
    }

    private void initPresent() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("hospId", hospitalId + "");
        presenter.getAllDepartment(params);
    }

    void initView(View view) {
        presenter = new DepartmentPresenter(new DepartmentModel(), this);
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                initPresent();
            }
        });

        deptList.setDivider(null);
        deptList.setOverscrollFooter(null);
        deptList.setOverscrollHeader(null);
        deptList.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        deptList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                backView.setVisibility(View.VISIBLE);
                deptTitleTv.setText(datas.get(position).getDepartment_name());
                refresh(datas.get(position));
            }
        });

        deptList.setDivider(null);
        deptList.setOverscrollFooter(null);
        deptList.setOverscrollHeader(null);
        deptList.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        peopleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                People people = (People) parent.getItemAtPosition(position);
//                UsersBean usersBean = (UsersBean) parent.getItemAtPosition(position);
                Intent intent = new Intent(getActivity(), Act_PeopleDetail.class);
                intent.putExtra("name", people.getUserName());
                intent.putExtra("mobile", people.getMobile());
                intent.putExtra("phone", people.getPhone());
                intent.putExtra("phone2", people.getPhone2());
                intent.putExtra("dept", people.getDepartmentName());
                intent.putExtra("job", people.getPosition());
                intent.putExtra("mail", people.getEmail());
                intent.putExtra("jobnum", people.getJobNum());
                startActivity(intent);
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.dept_back)
    public void onClick() {
        refresh(groupDataBean);
        backView.setVisibility(View.GONE);
        deptTitleTv.setText("");
    }

    @Override
    public void showGroupDatas(final BaseEntity<GroupDataBean> groupBean) {
        if ("200".equals(groupBean.getStatus())) {
            groupDataBean = groupBean.getDatas().get(0).getChildDepartments().get(0);
            refresh(groupDataBean);
        } else {
            emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }
    }

    private void refresh(GroupDataBean groupDataBean) {
        emptyLayout.dismiss();
        datas = groupDataBean.getChildDepartments();
        List<UsersBean> usersBeen = groupDataBean.getUsers();
        ArrayList<People> peoples = new ArrayList<>();
        adapter_dept = new DepartmentListAdapter(getContext(), datas, 0);
        deptList.setAdapter(adapter_dept);

        if (usersBeen != null) {
            for (UsersBean usersBean : usersBeen) {
                People people = new People();
                people.setUserName(usersBean.getUser_name());
                people.setJobNum(usersBean.getJobNum());
                people.setDepartmentName(groupDataBean.getDepartment_name());
//            people.setPosition(usersBean.getPosition());
//            people.setPinyin(usersBean.getPinyin());
                people.setUserId(usersBean.getUser_id());
                people.setPhone(usersBean.getTelephone1());
                people.setPhone2(usersBean.getTelephone2());
                people.setEmail(usersBean.getEmail());
                people.setMobile(usersBean.getPhoneNo());
                people.setRankOrder(usersBean.getRankOrder());
                peoples.add(people);
            }

            Collections.sort(peoples, new Comparator<People>() {
                @Override
                public int compare(People o1, People o2) {
                    return Integer.parseInt(o1.getRankOrder()) - Integer.parseInt(o2.getRankOrder());
                }
            });
        }

        if (adapter_people == null) {
            adapter_people = new ContractAdapter(getActivity(), peoples, 0, peopleList);
            peopleList.setAdapter(adapter_people);
        } else {
            adapter_people.setData(peoples);
        }
    }
}
